﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using Presentation;

namespace Infrastructure
{
    public class HtmlLogger : ILogger
    {
        private readonly string logFile;

        public HtmlLogger(string logFile = "log.html")
        {
            this.logFile = logFile;
            var log = CreateHtml();
            log.Save(logFile);
        }

        private static XmlDocument CreateHtml()
        {
            var log = new XmlDocument();
            var html = log.AppendChild(log.CreateElement("html"));
            var head = html.AppendChild(log.CreateElement("head"));
            head.AppendChild(log.CreateElement("body"));
            return log;
        }

        public void Write(string message)
        {
            var log = new XmlDocument();
            log.Load(logFile);
            var body = log.GetElementsByTagName("body")[0];
            var p = body.AppendChild(log.CreateElement("p"));
            p.InnerText = DateTime.Now.ToString() + ": " + message;
            log.Save(logFile);
        }

        public string Read()
        {
            var log = new XmlDocument();
            log.Load(logFile);
            var body = log.GetElementsByTagName("body")[0];
            var content = new StringBuilder();
            if (body.HasChildNodes)
            {
                foreach (XmlNode node in body.ChildNodes)
                {
                    content.AppendLine(node.InnerText);
                }
            }
            return content.ToString();
        }
    }
}
